package com.zsc.roadsys.realm;

import com.zsc.roadsys.entity.User;
import com.zsc.roadsys.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

@Controller
public class MyRealm extends AuthorizingRealm{
    @Autowired
    private UserService userService;

    /**自定义授权方法:获取当前登录用户的角色、权限信息，返回给shiro用来进行授权认证*/
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("自定义授权方法");
        //1获取用户身份信息
        String principal = principalCollection.getPrimaryPrincipal().toString();
        //2调用业务层获取用户的角色信息（数据库）

        //2.5调用业务层获取用户的权限信息（数据库）

        //3创建对象，封装当前登录用户的角色、权限信息
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String name = authenticationToken.getPrincipal().toString();
        User user = userService.getUserByUsername(name);
        if (user != null) {
            AuthenticationInfo info = new SimpleAuthenticationInfo(
                    authenticationToken.getPrincipal(),
                    user.getPassword(),
                    ByteSource.Util.bytes("salt"),
                    authenticationToken.getPrincipal().toString()
            );
            return info;
        }
        return null;
    }

}
